package com.group.controller;

import java.text.ParseException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.aliyuncs.afs.model.v20180112.AuthenticateSigRequest;
import com.aliyuncs.afs.model.v20180112.AuthenticateSigResponse;
import org.eclipse.jetty.util.UrlEncoded;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.RedirectView;

import com.base.view.GeneralResult;
import com.group.model.*;
import com.group.util.AESUtiles;
import com.group.util.NoteException;
import com.group.view.ActivityView;

/*
 * 活动接口
 * 
 * @author zhaolei
 */

@Controller
public class ActivityController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ActivityController.class);

	/**
	 * 查询活动日期
	 * 当前用户id
	 * @param request request
	 * @return ActivityView
	 * @throws ParseException parseEx
	 */
	@GetMapping("/activity/date/query")
	@ResponseBody
	public GeneralResult<ActivityView> queryActivityDate(HttpServletRequest request) throws ParseException {
		User user = getUser(request);
		Long userId = user.getId();
		if (userId == null)
			throw new NoteException("userId 不能为空");

		ActivityView view = new ActivityView();
		List<ActivityDate> dates = beanDao.queryList(new ActivityDate());

		double count = 0d;
		int days = 0;

		view.setActivityDates(dates);

		// 补充签到详情
		for (ActivityDate date : dates) {
			if (df.parse(date.getDate()).after(new Date())) {
				break;
			}
			ActivityLog log = new ActivityLog();
			log.setUserId(userId);
			log.setActivityDateId(date.getId());

			log = beanDao.queryOne(log);
			if (log != null) {
				date.setIsSign(true);
				date.setNum(log.getNum());
				count += log.getNum();
				days++;
			} else {
				date.setIsSign(false);
				date.setNum(0d);
				days = 0;
			}

		}

		view.setDays(days);
		view.setCount(count);

		// // 补充未签到的币的数字
		// for (ActivityDate date : dates) {
		// // 当天之后的处理
		// if (df.parse(date.getDate()).after(new Date())) {
		// date.setIsSign(null);
		// days = days + 1;
		// double num = 0d;
		// if (days == 1) {
		// num = 0.5;
		// } else if (days == 2) {
		// num = 1;
		// } else if (days == 3) {
		// num = 1.25;
		// } else if (days == 4) {
		// num = 1.5;
		// } else if (days == 5) {
		// num = 1.75;
		// } else if (days == 6) {
		// num = 2;
		// } else if (days == 7) {
		// num = 2.5;
		// } else if (days == 8) {
		// num = 3;
		// } else if (days == 9) {
		// num = 3.5;
		// } else if (days == 10) {
		// num = 4;
		// } else if (days == 11) {
		// num = 5;
		// } else if (days == 12) {
		// num = 6;
		// } else if (days == 13) {
		// num = 7;
		// } else if (days == 14) {
		// num = 8;
		// } else if (days == 15) {
		// num = 9;
		// }
		// date.setNum(num);
		// } else {
		// continue;
		// }
		//
		// }
		//
		// // 判断签到几天
		// signDays.put(userId, days);

		return new GeneralResult<ActivityView>().setValue(view);
	}


	/**
	 * 签到
	 * @param request request
	 * @param activityDateId 活动时间id
	 * @return ActivityLog
	 * @throws ParseException parseEx
	 */
	@GetMapping("/activity/date/sign")
	@ResponseBody
	public synchronized GeneralResult<ActivityLog> addActivityLog(HttpServletRequest request, Long activityDateId) throws ParseException {
		User user = getUser(request);
		Long userId = user.getId();

		if (activityDateId == null || userId == null)
			throw new NoteException("参数不能为空");

		ActivityDate date = beanDao.quickQueryOneById(ActivityDate.class, activityDateId);
		String dateStr = df.format(new Date());
		if (date == null || !dateStr.equals(date.getDate()))
			throw new NoteException("签到日期错误");

		ActivityLog log = new ActivityLog();
		log.setUserId(userId);
		log.setActivityDateId(activityDateId);
		if (beanDao.queryOne(log) != null) {
			throw new NoteException("已经签到过");
		}

		// 判断签到天数
		int days = 0;

		ActivityLog para = new ActivityLog();
		para.setUserId(userId);
		para.setActivityDateId(activityDateId - 1);
		ActivityLog exist = beanDao.queryOne(para);
		while (exist != null) {
			days++;
			para.setActivityDateId(para.getActivityDateId() - 1);
			exist = beanDao.queryOne(para);
		}

		// 增加签到当天
		days = days + 1;
		double num = 0d;
		if (days == 1) {
			num = 1.5;
		} else if (days == 2) {
			num = 1.8;
		} else if (days == 3) {
			num = 2.1;
		} else if (days == 4) {
			num = 2.4;
		} else if (days == 5) {
			num = 2.7;
		} else if (days == 6) {
			num = 3;
		} else if (days == 7) {
			num = 3.3;
		} else if (days == 8) {
			num = 3.6;
		} else if (days == 9) {
			num = 3.9;
		} else if (days == 10) {
			num = 4.2;
		} else if (days == 11) {
			num = 4.5;
		} else if (days == 12) {
			num = 5.1;
		} else if (days == 13) {
			num = 5.7;
		} else if (days == 14) {
			num = 6.3;
		} else if (days == 15) {
			num = 6.9;
		} else if (days == 16) {
			num = 7.5;
		} else if (days == 17) {
			num = 8.1;
		} else if (days == 18) {
			num = 8.7;
		} else if (days == 19) {
			num = 9.3;
		} else if (days == 20) {
			num = 10.5;
		} else if (days == 21) {
			num = 12;
		} else if (days == 22) {
			num = 13.5;
		} else if (days == 23) {
			num = 15;
		} else if (days == 24) {
			num = 16.5;
		} else if (days == 25) {
			num = 18;
		} else if (days == 26) {
			num = 19.5;
		} else if (days == 27) {
			num = 21;
		} else if (days == 28) {
			num = 22.5;
		} else if (days == 29) {
			num = 24;
		} else if (days == 30) {
			num = 25.5;
		}

		log.setNum(num);
		beanDao.save(log);

		// 增加用户钱包
		// UserTicker ut = new UserTicker();
		// ut.setUserId(userId);
		// ut.setCid("czr");
		// UserTicker utexist = beanDao.queryOne(ut);
		// if (utexist != null) {
		// utexist.setNum(utexist.getNum() + log.getNum());
		// beanDao.save(utexist);
		//
		// } else {
		// ut.setNum(log.getNum().doubleValue());
		// beanDao.save(ut);
		// }
		tickerService.addTicker(userId, "wecc", log.getNum(), "签到", null);

		return new GeneralResult<ActivityLog>().setValue(log);
	}

	/**
	 * 发送红包跳转 跳转时候带state 参数: 0 未中奖, 1 中奖 , 2 0-8点不能抽奖, 3 红包挂完 4.今日已经抽过 5. 红包活动结束
	 * 
	 * @param request request
     * @param para para
	 * @return RedirectView
	 */
	@GetMapping("/activity/redpack")
	public RedirectView getRedPack(HttpServletRequest request, String para) {
		// 判断url是否有效
		String para1 = getSystemParaValue("para");
		if (!para1.equals(para)) {
			throw new NoteException("url 无效");
		}

		// 判断活动发否开启
		String s = getSystemParaValue("redpack");
		String baseurl = getSystemParaValue("redpackurl");

		if ("0".equals(s)) {
			return new RedirectView(baseurl + "?state=" + 5);
		}

		String openid = getUserOpenid(request);

		// 判断用户当天是否抽过
		String date = df.format(new Date());
		RedPackLog log = new RedPackLog();
		log.setOpenid(openid);
		log.setDate(date);

		RedPackLog exist = beanDao.queryOne(log);
		if (exist != null) {
			return new RedirectView(baseurl + "?state=6&isWin=" + exist.getIsWin() + "&money=" + exist.getMoney());
		}

		// 判断是新老用户
		User user = beanDao.quickQueryOne(User.class, "openid", openid);
		int rate = 0;
		if (df.format(user.getCreateTime()).equals(date)) {
			// 新用户
			rate = getSystemParaValueInt("rate");
		} else {
			// 老用户
			rate = getSystemParaValueInt("oldrate");
		}

		Random r = new Random();
		int win = r.nextInt(10000);
		log.setWinRate(rate);
		if (win <= rate) {
			// 中奖
			log.setIsWin(1);
			beanDao.save(log);
			return new RedirectView(baseurl + "?state=" + 1 + "&logId=" + log.getId());
		} else {
			// 不中奖
			log.setIsWin(0);
			beanDao.save(log);
			return new RedirectView(baseurl + "?state=" + 0);
		}

	}

	/**
	 * 发送红包
	 * @param logId logId
	 * @param session session
	 * @param sig sig
	 * @param token token
	 * @param scene scene
	 * @param httpServletRequest request
	 * @return redirectView
	 */
	@RequestMapping(value = "/redpack/send", method = RequestMethod.GET)
	@ResponseBody
	public RedirectView sendRedPack(Long logId, String session, String sig, String token, String scene, HttpServletRequest httpServletRequest) {
		if (logId == null) {
			throw new NoteException("logId 不能为空");
		}

		String openid = getUserOpenid(httpServletRequest);

		logger.info("logId:" + logId + " , session = " + session + " , sig = " + sig + " , token = " + token + " , scene = " + scene);

		AuthenticateSigRequest request = new AuthenticateSigRequest();
		request.setSessionId(session);// 必填参数，从前端获取，不可更改，android和ios只变更这个参数即可，下面参数不变保留xxx
		request.setSig(sig);// 必填参数，从前端获取，不可更改
		request.setToken(token);// 必填参数，从前端获取，不可更改
		request.setScene(scene);// 必填参数，从前端获取，不可更改
		request.setAppKey("FFFF00000000017AE57E");// 必填参数，后端填写
		request.setRemoteIp("127.0.0.1");// 必填参数，后端填写

		try {
			AuthenticateSigResponse response = client.getAcsResponse(request);
			if (response.getCode() == 100) {
				System.out.println("验签通过");

				RedPackLog log = beanDao.quickQueryOneById(RedPackLog.class, logId);
				if (log.getIsSend() == 1) {
					throw new NoteException("已经发送过");
				}

				Random r = new Random();
				int money = 100 + r.nextInt(10);
				String timeStamp = System.currentTimeMillis() + "";
				String str = "timeStamp=" + timeStamp + "&openid=" + openid + "&money=" + money;
				String md5Str = AESUtiles.Encrypt(str);

				// logger.info("加密前:" + str + ", 加密后:" + md5Str);
				// logger.info("解密后:" + AESUtiles.Decrypt(md5Str));

				String baseurl = getSystemParaValue("redpackurl");
				String redirectUrl = baseurl + "?state=6&isWin=" + 1 + "&money=" + money;
				redirectUrl = UrlEncoded.encodeString(redirectUrl);
				md5Str = UrlEncoded.encodeString(md5Str);

				log.setMoney(money);
				log.setIsSend(1);
				beanDao.save(log);

				String url = "http://pass2u.info/r/open/third/pay?timeStamp=" + timeStamp + "&redirectUrl=" + redirectUrl + "&echostr=" + md5Str + "&money=" + money + "&openid=" + openid;

				logger.info("发送红包 url = " + url);
				return new RedirectView(url);
			} else {
				System.out.println("验签失败");
				logger.info(response.getMsg());
				logger.info(response.getDetail());
			}
			// TODO
		} catch (Exception e) {
			e.printStackTrace();
		}

		throw new NoteException("验证失败");
	}

	@RequestMapping(value = "/redpack/aes/test", method = RequestMethod.GET)
	@ResponseBody
	public GeneralResult<String> testAes() {
		String openid = "oBGKy022MbVzQOgukMlFuhfld5tM";
		Random r = new Random();
		int money = 100 + r.nextInt(10);
		String timeStamp = System.currentTimeMillis() + "";
		String str = "timeStamp=" + timeStamp + "&openid=" + openid + "&money=" + money;
		String md5Str = AESUtiles.Encrypt(str);

		logger.info("加密前:" + str + ", 加密后:" + md5Str);
		logger.info("解密后:" + AESUtiles.Decrypt(md5Str));

		return new GeneralResult<String>().setValue(md5Str);

	}

	@RequestMapping(value = "/redpack/aes/decode", method = RequestMethod.GET)
	@ResponseBody
	public GeneralResult<String> testDecode(String content) {
		logger.info("加密密文:" + content);

		return new GeneralResult<String>().setValue(AESUtiles.Decrypt(content));

	}

}
